package com.monitor.display_platform.core.exec;//package com.zy.datareceiver.core.exec;

import com.monitor.display_platform.core.common.SpringApplicationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class BaseThreadPoolExecutor {
    private static final Logger log = LoggerFactory.getLogger(BaseThreadPoolExecutor.class);

    @Value("core_pool_size")
    private static final int  corePoolSize=20;
    @Value("maximum_pool_size")
    private static final int maximumPoolSize = 20;
    @Value("keep_alive_time")
    private static final long keepAliveTime = 0;
    @Value("work_queue_size")
    private static final int workQueueSize = 200;


    @Bean("taskExecutor")
    public static ThreadPoolExecutor getThreadPoolExecutor(){
        final Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
            //可以捕捉到线程中的未捕获异常
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                log.error("线程 {} 运行时出现异常，出现的异常信息为 {} ,状态为 {}",t.getName(),e.getMessage(),t.getState());
                t.stop();
            }
        };

        final ThreadFactory threadFactory = new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);

                if (thread.isDaemon()){
                    thread.setDaemon(false);
                }
                if (Thread.NORM_PRIORITY == thread.getPriority()){
                    thread.setPriority(Thread.NORM_PRIORITY);
                }
                thread.setUncaughtExceptionHandler(exceptionHandler);
                return thread;
            }
        };

        final RejectedExecutionHandler rejectedExecutionHandler = new RejectedExecutionHandler(){
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

            }
        };

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(workQueueSize),
                threadFactory,
                rejectedExecutionHandler
        );
        return executor;
    }
}
